<template>
  <div class="container">
    <div class="u-title f-mtp10">
      <h2>权限管理</h2>
      <el-button
        size="mini"
        @click="addBtnClickEvent">添 加</el-button>
    </div>
    <div>
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column prop="departmentName" label="部门名称" width="180"></el-table-column>
        <el-table-column prop="departmentDesc" label="职能描述" width="180"></el-table-column>
        <el-table-column prop="membersNum" label="部门管理员数量" width="180"></el-table-column>
        <el-table-column prop="createTime" label="添加时间" width="180"></el-table-column>
        <el-table-column prop="createTime" label="是否启用" width="180">
          <template slot-scope="scope">
            <el-switch
              @change="enableDepartment(scope.$index, scope.row)"
              style="display: block"
              v-model="scope.row.isUse"
              active-color="#1ABC9C"
              inactive-color="#e4e4e4">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="enable" label="操作">
          <template slot-scope="scope">
            <router-link class='f-mrt10 s-c-green' to='/home/permissionSettings'>权限设置</router-link>
            <span class='f-mrt10 f-csp s-c-green' @click="editBtnClickEvent(scope.row)">编 辑</span>
            <el-button class='s-c-red' type="text" @click="handleDelete(scope.row.id)">删 除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage1"
          :page-size="100"
          layout="total, prev, pager, next"
          :total="1000">
        </el-pagination>
      </div>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="560px">
      <div>
        <div class='dialog-item flex'>
          <label for="">部门名称：</label>
          <div class='dialog-item-right'>
            <el-input v-model="departmentName" placeholder="输入部门名称"></el-input>
          </div>
        </div>
        <div class='dialog-item flex'>
          <label for="">职能描述：</label>
          <div class='dialog-item-right'>
            <el-input type="textarea" :rows=4 v-model="departmentDesc" placeholder="请输入内容"></el-input>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogHandleBtnClickEvent">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: 'PermissionManage',
  data() {
    return {
      dialogVisible: false,
      dialogTitle: '添加部门',
      selectDepartment: null,   // 选择编辑的部门
      isEdit: false,  // 是否修改状态
      value4: true,
      departmentName: '',
      departmentDesc: '',
      tableData: []
    }
  },
  created: function() {
    this.getList();
  },
  methods: {
    enableDepartment(index, item) {
      console.log('index::', index);
      console.log('item:::', item);
      const params = new URLSearchParams();
      params.append('id', item.id);
      console.log('item:::', item);
      const enable = item.isUse ? 1 : 0;
      params.append('enable', enable);
      this.updateDepartment(params);
    },
    handleSizeChange() {

    },
    // 编辑按钮点击事件
    editBtnClickEvent(item) {
      // const _this = this;
      this.dialogTitle = '修改部门信息';
      this.isEdit = true;
      this.dialogVisible = true;
      this.departmentName = item.departmentName;
      this.departmentDesc = item.departmentDesc;
      this.selectDepartment = item;
    },
    // 修改部门信息
    updateDepartment(params) {
      const _this = this;
      axios.post(`${this.GLOBAL.baseUrl}/api/admin/updateDepartmentById`, params, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      })
      .then((res) => {
        console.log(res);
        if (res.data.returnCode === 200) {
          // this.$router.push('/home');
          _this.$message({
            message: '恭喜你，修改成功！',
            type: 'success'
          });
          _this.dialogVisible = false;
          _this.getList();
        } else {
          _this.$message({
            message: res.data.message,
            type: 'warning'
          });
        }
      })
      .catch((error) => {
        console.log(error);
      });
    },

    // 获取部门列表
    getList() {
      console.log('getList::::----');
      const _this = this;
      axios.get(`${this.GLOBAL.baseUrl}/api/admin/getDepartmentList`).then(res => {
        console.log('res:::', res);

        if(res.data.returnCode == 200) {
          const list = res.data.data;
          for(let i = 0; i < list.length; i++) {
            list[i].isUse = list[i].enable == 1 ? true : false;
          }
          console.log('list:::', list);
          _this.tableData = list;
        }
      }).catch(err => {
        console.error('err::', err);
      })
    },

    dialogHandleBtnClickEvent() {
      if(!this.isEdit) {
        this.handleAdd();
      } else {
        const params = new URLSearchParams();
        params.append('id', this.selectDepartment.id);
        params.append('departmentName', this.departmentName);
        params.append('departmentDesc', this.departmentDesc);
        this.updateDepartment(params);
      }
    },

    // 添加部门
    handleAdd() {
      const _this = this;
      const params = new URLSearchParams();
      params.append('departmentName', this.departmentName);
      params.append('departmentDesc', this.departmentDesc);
      axios.post(`${this.GLOBAL.baseUrl}/api/admin/createDepartment`, params, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      })
      .then((res) => {
        console.log(res);
        if (res.data.returnCode === 200) {
          // this.$router.push('/home');
          _this.$message({
            message: '恭喜你，创建成功！',
            type: 'success'
          });
          _this.dialogVisible = false;
          _this.getList();
        } else {
          _this.$message({
            message: res.data.message,
            type: 'warning'
          });
        }
      })
      .catch((error) => {
        console.log(error);
      });
    },

    // 添加按钮点击事件
    addBtnClickEvent() {
      this.dialogTitle = '添加部门';
      this.dialogVisible = true;
      this.departmentName = '';
      this.departmentDesc = '';
    },

    // 根据id删除部门
    deleteDepartmentById(departmentId) {
      const _this = this;
      const params = new URLSearchParams();
      params.append('id', departmentId);
      axios.post(`${this.GLOBAL.baseUrl}/api/admin/deleteDepartmentById`, params, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      })
      .then((res) => {
        console.log(res);
        if (res.data.returnCode === 200) {
          // this.$router.push('/home');
          _this.$message({
            message: '删除成功！',
            type: 'success'
          });
          _this.getList();
        } else {
          _this.$message({
            message: res.data.message,
            type: 'warning'
          });
        }
      })
      .catch((error) => {
        console.log(error);
      });
    },

    // 删除按钮点击事件
    handleDelete(departmentId) {
      const _this = this;
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.deleteDepartmentById(departmentId);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.dialog-item{
  margin-bottom: 10px;
}
.dialog-item>label{
  width: 100px;
  line-height: 40px;
  text-align: right;
  margin-right: 10px;
}
.dialog-item>label::before{
  content: '*';
  line-height: 40px;
  color: red;
  margin-right: 5px;
}
.dialog-item-right{
  flex: 1;
}
</style>
